package ee.nutilovi.praktikaportaal.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import ee.nutilovi.praktikaportaal.tools.CryptoTools;
import ee.nutilovi.praktikaportaal.tools.VerificationTools;

@SuppressWarnings("serial")
public class SaveRegistrationServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		PrintWriter pw = resp.getWriter();

		String username = req.getParameter("username");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		String verify = req.getParameter("verify");
		boolean isAdmin = false;
		if (req.getParameter("admin") != null) {
			isAdmin = true;
		}
		
		boolean isValidUsername = VerificationTools.isValidUsername(username);
		boolean isValidEmail = VerificationTools.isValidEmail(email);
		boolean isValidPassword = VerificationTools.isValidPassword(password, verify);
		
		if (isValidUsername && isValidEmail && isValidPassword) {
			Entity u = new Entity("User", username);
			String salt = CryptoTools.createSalt();
			String pwString;
			try {
				pwString = CryptoTools.hashPassword(password, salt);
			} catch (NoSuchAlgorithmException e) {
				resp.sendRedirect("/error");
				return;
			}
			
			u.setProperty("email", email);
			u.setProperty("password", pwString);
			u.setProperty("admin", isAdmin);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			datastore.put(u);
			resp.sendRedirect("/welcome");
		} else {
			pw.println("Invalid input.");
		}
	}
}
